<template>
  <div v-if="GLOBAL.sysUserVisible=='1'">
    <el-form ref="searchForm" :model="searchForm" label-width="20px">
      <el-row gutter="20">
        <div v-if="GLOBAL.global_limit.includes('22')">
          <el-col :span="2" offset="0">
            <el-button type="primary" size="mini" @click=addChoose>新增用户</el-button>
          </el-col>
          <el-col :span="1" offset="0">
            <el-button type="warning" size="mini" @click="dialogForm3Visible = true">批量导入</el-button>
          </el-col>
        </div>
        <div v-if="GLOBAL.global_limit.includes('21')">
          <el-col :span="4" offset="2">
            <el-input v-model="queryInfo.stname" width="80px" size="small" suffix-icon="el-icon-search" clearable
                      placeholder="请输入用户姓名"></el-input>
          </el-col>
          <el-col :span="3">
            <el-select v-model="queryInfo.department" size="small" filterable clearable placeholder="请选择学校">
              <el-option
                v-for="item in departmentList"
                :key="item"
                :label="item"
                :value="item"/>
            </el-select>
          </el-col>
          <el-col :span="3">
            <el-select v-model="queryInfo.stype" size="small" filterable clearable placeholder="请选择用户类别">
              <el-option
                v-for="item in stypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-col>
          <el-col :span="7">
            <el-date-picker
              v-model="queryInfo.filterDates"
              value-format="yyyy-MM-dd"
              type="daterange"
              align="left"
              size="small"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" size="mini" @click="initData">搜索</el-button>
          </el-col>
        </div>
      </el-row>
    </el-form>
    <el-dialog title="新建用户信息" align="left" :visible.sync="dialogFormVisible">
      <el-form :model="addInfo" :rules="rules" label-width="100px" ref="addInfo">
        <el-form-item label="所属学校" prop="department">
          <el-input v-model="addInfo.department" disabled></el-input>
        </el-form-item>
        <el-form-item label="所属学院" prop="college">
          <el-select v-model="addInfo.college" placeholder="请选择学院">
            <el-option
              v-for="item in collegeInfo"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="stname">
          <el-input v-model="addInfo.stname"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="addInfo.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="addInfo.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="stype">
          <el-select v-model="addInfo.stype" placeholder="请选择类别">
            <el-option label="初中" :value="3"></el-option>
            <el-option label="高中" :value="4"></el-option>
            <el-option label="大专" :value="5"></el-option>
            <el-option label="本科" :value="0"></el-option>
            <el-option label="硕士" :value="1"></el-option>
            <el-option label="博士" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="year">
          <el-date-picker
            v-model="addInfo.year"
            type="year"
            value-format="yyyy"
            placeholder="选择年">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学工号" prop="stid">
          <el-input v-model="addInfo.stid"></el-input>
        </el-form-item>
        <el-form-item label="生源地 省份" prop="province">
          <el-select v-model="addInfo.province" placeholder="请选择省份">
            <el-option
              v-for="item in provinceInfo"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click=addUser>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="编辑用户信息" align="left" :visible.sync="dialogForm2Visible">
      <el-form :model="editInfo" :rules="rules" label-width="100px" ref="editInfo">
        <el-form-item label="所属学校" prop="department">
          <el-input v-model="editInfo.department" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="所属学院" prop="college">
          <el-input v-model="editInfo.college" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="stname">
          <el-input v-model="editInfo.stname"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editInfo.age"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editInfo.gender" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类别" prop="stype">
          <el-select v-model="editInfo.stype" placeholder="请选择类别">
            <el-option label="初中" :value="3"></el-option>
            <el-option label="高中" :value="4"></el-option>
            <el-option label="大专" :value="5"></el-option>
            <el-option label="本科" :value="0"></el-option>
            <el-option label="硕士" :value="1"></el-option>
            <el-option label="博士" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="year">
          <el-input v-model="editInfo.year" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="学工号" prop="stid">
          <el-input v-model="editInfo.stid" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="生源地 省份" prop="province">
          <el-select v-model="editInfo.province" placeholder="请选择省份">
            <el-option
              v-for="item in provinceInfo"
              :key="item.label"
              :label="item.label"
              :value="item.label">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm2Visible = false">取 消</el-button>
        <el-button type="primary" @click=Edit>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="请选择文件" width="500px" align="left" :visible.sync="dialogForm3Visible">
      <el-form :model="addInfo">
        <el-form-item>
          <el-upload ref="upload"
                     accept=".xls,.xlsx"
                     action="#"
                     :limit="limit"
                     :auto-upload="false"
                     :multiple="false"
                     :file-list="fileList"
                     :before-upload="beforeUpload"
                     :http-request="uploadHttpRequest"
                     :on-remove="fileRemove"
                     :on-change="fileChange"
                     :on-success="handleSuccess"
                     :on-error="handleError">
            <el-button size="small" type="primary">选择文件</el-button>
            <div slot="tip" class="el-upload__tip">一次只能上传一个xls/xlsx文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <!--          <el-link href="https://follwup.cmas2020.cn/demo.xlsx">点击下载示例文件</el-link>-->
          <el-link href="https://follwup-test.cmas2020.cn/demo.xlsx">点击下载示例文件</el-link>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取 消</el-button>
        <el-button type="success" size="small" @click="submitUpload">上 传</el-button>
      </div>
    </el-dialog>
    <el-table
      stripe
      v-loading="listLoading"
      :row-style="{height:'45px'}"
      :cell-style="{padding:'0px'}"
      style="font-size: 14px;width: 100%"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      :data=userManagementTable>
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="60">
      </el-table-column>
      <el-table-column
        align="center"
        prop="department"
        label="所属学校"
        width="160"
        :show-overflow-tooltip='true'>
      </el-table-column>
      <el-table-column
        align="center"
        prop="college"
        label="所属学院"
        width="160"
        :show-overflow-tooltip='true'>
      </el-table-column>
      <el-table-column
        align="center"
        prop="stname"
        label="姓名"
        width="100"
        :show-overflow-tooltip='true'>
      </el-table-column>
      <el-table-column
        align="center"
        prop="gender"
        label="性别"
        width="80">
        <template slot-scope="scope">
          <el-span v-if=" scope.row.gender == '男' " class="el-icon-male" style="font-size:20px;color:blue"></el-span>
          <el-span v-else-if="scope.row.gender == '女' " class="el-icon-female"
                   style="font-size:20px;color:red"></el-span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="stype"
        label="类别"
        width="120">
        <template slot-scope="scope">
          <el-tag v-if=" scope.row.stype == 0" type="primary">本科</el-tag>
          <el-tag v-else-if="scope.row.stype == 1" type="success">硕士</el-tag>
          <el-tag v-else-if="scope.row.stype == 2" type="danger">博士</el-tag>
          <el-tag v-else-if="scope.row.stype == 3" type="danger">初中</el-tag>
          <el-tag v-else-if="scope.row.stype == 4" type="danger">高中</el-tag>
          <el-tag v-else-if="scope.row.stype == 5" type="danger">大专</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="year"
        label="年级"
        width="100">
      </el-table-column>
      <el-table-column
        align="center"
        label="隐私信息"
        width=120>
        <template slot-scope="scope">
          <el-popover trigger="click" placement="top">
            <p>年龄: {{ scope.row.age }}</p>
            <p>学工号: {{ scope.row.stid }}</p>
            <p>生源地: {{ scope.row.province }}</p>
            <div slot="reference" class="name-wrapper">
              <el-botton type="text" size="mini">点击查看>></el-botton>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="create_time"
        label="创建时间"
        width="160"
        :show-overflow-tooltip='true'>
      </el-table-column>
      <el-table-column align="center" label="设置">
        <template slot-scope="scope">
            <span v-if="GLOBAL.global_limit.includes('23')">
              <el-button
                size="mini"
                @click="handleEdit(scope.row)">编辑</el-button>
            </span>
          <span v-if="GLOBAL.global_limit.includes('24')">
              <el-button
                size="mini"
                type="danger"
                @click="Delete(scope.row)">删除</el-button>
            </span>
        </template>
      </el-table-column>
    </el-table>
    <div class="el-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 8, 10, 15]"
        :page-size="queryInfo.pageSize"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
  </div>
</template>
<script>
    import {regionData, CodeToText} from "element-china-area-data";

    export default {
        data() {
            return {
                rules: {
                    department: [
                        {required: true, message: '请选择学校'},
                    ],
                    college: [
                        {required: true, message: '请选择学院'},
                    ],
                    stname: [
                        {required: true, message: '请输入姓名'},
                    ],
                    gender: [
                        {required: true, message: '请选择性别'},
                    ],
                    stype: [
                        {required: true, message: '请选择类别'},
                    ],
                    year: [
                        {required: true, message: '请选择年级'},
                    ],
                    stid: [
                        {required: true, message: '请输入学号'},
                    ],
                    province: [
                        {required: true, message: '请选择生源地省份'},
                    ]
                },
                userManagementTable: [],
                schoolInfo: {},
                collegeInfo: [],
                provinceInfo: [],
                queryInfoCon: {
                    stname: null,
                    department: null,
                    stype: null,
                    filterDates: ["", ""]
                },
                queryInfo: {
                    stname: null,
                    department: null,
                    stype: null,
                    filterDates: ["", ""],
                    pageNum: 1,
                    pageSize: 10
                },
                addInfo: {
                    department: null,
                    college: null,
                    stname: null,
                    gender: null,
                    age: null,
                    stid: null,
                    stype: null,
                    province: null,
                    year: null,
                    create_time: null
                },
                editInfo: {
                    infoid: null,
                    department: null,
                    college: null,
                    stname: null,
                    gender: null,
                    age: null,
                    stid: null,
                    stype: null,
                    province: null,
                    year: null,
                    create_time: null
                },
                delInfo: {
                    infoid: null,
                },
                dialogFormVisible: false,
                dialogForm2Visible: false,
                dialogForm3Visible: false,
                noTime: null,
                total: 0,
                limit: 1,
                self_errorMsg: null,
                departmentList: [
                    '华中科技大学',
                    '武汉大学'
                ],
                stypeList: [{
                    label: '初中',
                    value: 3
                }, {
                    label: '高中',
                    value: 4
                }, {
                    label: '大专',
                    value: 5
                }, {
                    label: '本科',
                    value: 0
                }, {
                    label: '硕士',
                    value: 1
                }, {
                    label: '博士',
                    value: 2
                }],
                fileList: []
            }
        },
        watch: {
            schoolInfo() {
                this.$nextTick(() => {
                    //此时就可以获取到在created赋值后的dataList了
                    this.getCollegeInfo();

                })
            },
        },
        created() {
            this.initData();
            this.getUniversityInfo();
            this.getTime()
            this.dealProvince()
        },
        methods: {
            //获取学校信息
            getUniversityInfo() {
                this.$axios.post("managementSystem/university/getAllNameByUid")
                    .then(data => {
                        if (data.status != 200) {
                            this.$message.error('服务出错' + data.status);
                        } else {
                            if (data.data.errorCode == '200') {
                                var u = data.data.schoolNameList
                                this.schoolInfo = u[0]
                            }
                        }
                    })
            },
            //获取学院信息
            getCollegeInfo() {
                //获取学院信息
                this.$axios.post("managementSystem/college/findbyUid", {"uid": this.schoolInfo["id"]})
                    .then(data => {
                        if (data.status != 200) {
                            this.$message.error('服务出错' + data.status);
                        } else {
                            if (data.data.errorCode == '200') {
                                var u = data.data.data
                                for (var i in u) {
                                    this.collegeInfo.push({"id": u[i]["collegeId"], "label": u[i]["collegeName"]})
                                }
                            }
                        }
                    })
            },
            //处理省份规则
            dealProvince() {
                for (var i = 0; i < regionData.length; i++) {
                    this.provinceInfo.push({"id": regionData[i]["value"], "label": regionData[i]["label"]})
                }
            },
            //获取当前时间
            getTime() {
                var today = new Date()
                this.nowTime = today.toLocaleDateString()
                var reg = new RegExp("/", "g");
                this.nowTime = this.nowTime.replace(reg, "-")
            },
            //提交查询信息
            initData() {
                if (this.queryInfo.filterDates == null)
                    this.queryInfo.filterDates = ["", ""]
                if (this.queryInfo.stname != this.queryInfoCon.stname || this.queryInfo.department != this.queryInfoCon.department
                    || this.queryInfo.stype != this.queryInfoCon.stype || this.queryInfo.filterDates != this.queryInfoCon.filterDates) {
                    this.queryInfo.pageNum = 1
                    this.queryInfoCon.stname = this.queryInfo.stname
                    this.queryInfoCon.department = this.queryInfo.department
                    this.queryInfoCon.stype = this.queryInfo.stype
                    this.queryInfoCon.filterDates = this.queryInfo.filterDates
                }
                var allData
                this.$axios.post("managementSystem/student/find", this.queryInfo)
                    .then(data => {
                        if (data.status != 200) {
                            this.$message.error('服务出错' + data.status);
                            // this.$message(fgf{
                            //   message:'服务错误',
                            //   type:'warn'
                            // });
                        } else {
                            if (data.data.errorCode == '200') {
                                allData = data.data
                                console.log(allData.errorMsg)
                                this.userManagementTable = allData.userManagementTable
                                // for(var i=0;i<this.userManagementTable.length;i++){
                                //     this.userManagementTable[i]["create_time"]=this.userManagementTable[i]["create_time"].substring(0,10)
                                // }
                                this.departmentList = allData.departmentList
                                this.total = allData.totalNum
                                this.addInfo = {
                                    department: null,
                                    college: null,
                                    stname: null,
                                    gender: null,
                                    age: null,
                                    stid: null,
                                    stype: null,
                                    province: null,
                                    year: null,
                                    create_time: null
                                }
                            }
                        }
                    })
            },
            //监听 页面尺寸 改变
            handleSizeChange(newSize) {
                this.queryInfo.pageSize = newSize
                this.initData()
            },
            // 监听 页码值 改变的事件
            handleCurrentChange(newPage) {
                // console.log(newPage)
                this.queryInfo.pageNum = newPage
                this.initData()
            },
            handleEdit(row) {  //进入编辑表单
                if (this.$refs['editInfo'] != null) {
                    this.$refs['editInfo'].resetFields()
                }
                console.log(row.create_time)
                this.editInfo.infoid = row.infoid    //直接用this.editInfo=row 传会有问题
                this.editInfo.department = row.department
                this.editInfo.college = row.college
                this.editInfo.stname = row.stname
                this.editInfo.gender = row.gender
                this.editInfo.age = row.age
                this.editInfo.stid = row.stid
                this.editInfo.stype = row.stype
                this.editInfo.province = row.province
                this.editInfo.year = row.year
                this.editInfo.create_time = row.create_time
                this.dialogForm2Visible = true
            },
            Edit() {  //提交编辑内容
                this.$refs.editInfo.validate((valid) => {
                    if (valid) {
                        console.log(this.editInfo.create_time)
                        this.dialogForm2Visible = false
                        var allData
                        this.$axios.post("managementSystem/student/edit", this.editInfo)
                            .then(data => {
                                if (data.status != 200) {
                                    this.$message.error('服务出错' + data.status);
                                    // this.$message(fgf{
                                    //   message:'服务错误',
                                    //   type:'warn'
                                    // });
                                } else {
                                    if (data.data.errorCode == '200') {
                                        allData = data.data
                                        console.log(allData.errorMsg)
                                        this.$message({
                                            type: 'success',
                                            message: '修改成功!'
                                        })
                                        this.initData()
                                    }
                                }
                            })
                    }
                })
            },
            Delete(row) {
                this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'danger',
                    center: true
                }).then(() => {
                    this.delInfo.infoid = row.infoid
                    this.$axios.post("managementSystem/student/delete", this.delInfo)
                        .then(data => {
                            if (data.status != 200) {
                                this.$message.error('服务出错' + data.status);
                                // this.$message(fgf{
                                //   message:'服务错误',
                                //   type:'warn'
                                // });
                            } else {
                                if (data.data.errorCode == '200') {
                                    console.log("删除表项：", this.delInfo.id, data.data.errorMsg)
                                    this.initData()
                                }
                            }
                        })
                    this.$message({
                        type: 'success',
                        message: '学生删除成功!'
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            addChoose() {
                if (this.$refs['addInfo'] != null) {
                    this.$refs['addInfo'].resetFields()
                }
                this.addInfo = {
                    department: this.schoolInfo["universityName"],
                    college: null,
                    stname: null,
                    gender: null,
                    age: null,
                    stid: null,
                    stype: null,
                    province: null,
                    year: null,
                    create_time: null
                }
                this.dialogFormVisible = true
            },
            addUser() {
                this.$refs.addInfo.validate((valid) => {
                    if (valid) {
                        this.getTime()
                        this.addInfo.create_time = this.nowTime
                        console.log(this.addInfo.create_time)
                        var allData
                        this.$axios.post("managementSystem/student/insert", this.addInfo)
                            .then(data => {
                                if (data.status != 200) {
                                    this.$message.error('服务出错' + data.status);
                                } else {
                                    if (data.data.errorCode == '200') {
                                        allData = data.data
                                        console.log(allData.errorMsg)
                                        this.$message({
                                            type: 'success',
                                            message: '添加成功!'
                                        })
                                        this.dialogFormVisible = false;
                                        this.initData()
                                    } else if (data.data.errorCode == '502') {
                                        this.$message({
                                            type: 'warning',
                                            message: '没有该院系！'
                                        })
                                    }
                                }
                            })
                    }
                })
            },
            //上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
            beforeUpload(file) {
                //文件类型
                const isType = file.type === 'application/vnd.ms-excel'
                const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                const fileType = isType || isTypeComputer
                if (!fileType) {
                    this.$message.error('上传文件只能是xls/xlsx格式！')
                }

                // 文件大小限制为10M
                const fileLimit = file.size / 1024 / 1024;
                if (fileLimit > 10) {
                    this.$message.error('上传文件大小不超过10M！');
                }
            },
            // 自定义上传方法
            uploadHttpRequest() {
                var vm = this
                if (this.fileList.length === 0) {
                    this.$message.warning('请上传文件');
                } else {
                    let form = new FormData();
                    form.append('file', this.fileList[0]["raw"]);
                    for (var key in this.fileList[0]) {
                        console.log("属性：" + key + ",值：" + this.fileList[0][key]);
                    }
                    console.log("类型：" + typeof this.fileList[0]["raw"])
                    this.$axios({
                        method: "post",
                        url: "managementSystem/student/import",
                        headers: {
                            'Content-type': 'multipart/form-data'
                        },
                        data: form
                    }).then(data => {
                        console.log(data)
                        if (data.status != 200) {
                            console.log("导入失败")
                            this.$message.error('导入失败');
                        } else {
                            if (data.data.errorCode === 200) {
                                this.$message({
                                    message: '导入成功',
                                    type: 'success'
                                });
                                this.initData();
                                this.closeDialog();
                            } else {
                                this.$message.error('导入失败');
                            }

                        }
                    })
                        .catch(function (error) {
                            vm.$message.error('导入失败');
                        });
                }
            },
            submitUpload() {
                this.$refs.upload.submit()
                this.initData()
            },
            // 文件上传成功时的钩子
            handleSuccess(res, file, fileList) {
                this.$message.success('文件上传成功');
            },
            // 文件上传失败时的钩子
            handleError(err, file, fileList) {
                this.$message.error('文件上传失败');
            },
            // 文件发生改变
            fileChange(file, fileList) {
                if (fileList.length > 0) {
                    this.fileList = [fileList[fileList.length - 1]] // 展示最后一次选择的文件
                }
            },
            // 移除选择的文件
            fileRemove(file, fileList) {
                if (fileList.length < 1) {
                    this.uploadDisabled = true //未选择文件则禁用上传按钮
                }
            },
            // 取消
            closeDialog() {
                this.$refs.upload.clearFiles() //清除上传文件对象
                this.fileList = [] //清空选择的文件列表
                this.$emit('close', false)
                this.dialogForm3Visible = false
            }

        }
    }

</script>
<style scoped>

</style>
